package com.postracker.postracker.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DataBase {

	private static final int DEFAULT_TIMEOUT = 30;

	private String connectionDriver;
	private String connectionUrl;
	private Connection connection;
	private Statement statement;

	protected DataBase(String driver, String url) {
		connectionDriver = driver;
		connectionUrl = url;
		loadConnectionDriver();
	}

	private void loadConnectionDriver() {
		try {
			Class.forName(connectionDriver);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("Connection Driver not found"
					+ connectionDriver, e);
		}
	}

	public void openConnection() throws SQLException {
		connection = DriverManager.getConnection(connectionUrl);
	}

	private void createNewStatement() throws SQLException {
		statement = connection.createStatement();
		statement.setQueryTimeout(DEFAULT_TIMEOUT);
	}

	public void executeStmt(String instruction) throws SQLException {
		createNewStatement();
		statement.executeUpdate(instruction);
	}

	public ResultSet executeQry(String instruction) throws SQLException {
		createNewStatement();
		return statement.executeQuery(instruction);
	}

	public void closeConnection() throws SQLException {
		connection.close();
	}

}
